package com.learn.algorithm_may_3;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * 给出两个 非空 的链表用来表示两个非负的整数。其中，它们各自的位数是按照 逆序 的方式存储的，并且它们的每个节点只能存储 一位 数字。
   如果，我们将这两个数相加起来，则会返回一个新的链表来表示它们的和。
   您可以假设除了数字 0 之外，这两个数都不会以 0 开头。

     输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
     输出：7 -> 0 -> 8
     原因：342 + 465 = 807

     342 + 658 = 1000

   来源：力扣（LeetCode）
   链接：https://leetcode-cn.com/problems/add-two-numbers
 */
public class Solution {

    private static final Logger logger = LoggerFactory.getLogger(Solution.class);

    public static void main(String[] args) {
        new Solution().test();
    }

    public void test(){
        ListNode node1 = new ListNode(2);
        node1.next = new ListNode(4);
        node1.next.next = new ListNode(3);
        node1.next.next.next = new ListNode(3);

        ListNode node2 = new ListNode(5);
        node2.next = new ListNode(6);
        node2.next.next = new ListNode(4);

        ListNode result = new ListNode(0);
        addTwoNumbers(node1, node2, result, 0);
        logger.info("{} -> {} -> {}", result.val, result.next.val, result.next.next.val);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2, ListNode r, int carry) {

        int l1_val = 0;
        int l2_val = 0;
        if(l1 != null) l1_val = l1.val;
        if(l2 != null) l2_val = l2.val;

        //- 两数相加
        int first = l1_val + l2_val + carry;
        //- 归零
        carry = 0;
        if (first > 9){
            carry = first / 10;
            int j = first % 10;
            if (r.next == null){
                r.next = new ListNode(j);
            }
            r.val = j;
        }else {
            if (r.next == null){
                r.next = new ListNode(first);
            }
            r.val = first;
        }

        System.out.println(r.val);

        ListNode l1_next = null;
        ListNode l2_next = null;
        if (l1 != null) l1_next = l1.next;
        if (l2 != null) l2_next = l2.next;

        if (l1_next != null || l2_next != null || carry != 0){
            addTwoNumbers(l1_next, l2_next, r.next, carry);
        }

        return r;

    }

}

/**
 * Definition for singly-linked list.
 */
class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

